from django.shortcuts import render, redirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.decorators import login_required

from user.models import CdUser


# Create your views here.
def user_login(request):
    """ 登录 """
    # GET请求
    if request.method == "GET":
        # 从 Sesison 中 获取错误信息
        err_info = request.session.pop('error_info', '')
        return render(
            request,
            "user/login.html",
            context={'error_info': err_info}
        )

    # 获取 表单提交的 POST 请求
    user = request.POST.get("username", "")
    pwd = request.POST.get("password", "")
    # 数据库用户查询查询
    if not CdUser.objects.filter(username=user):
        request.session["error_info"] = "用户名不存在"
        return redirect("/user/login")

    user_obj = auth.authenticate(username=user, password=pwd)
    if user_obj:
        auth.login(request, user_obj)
        return redirect('/')
    request.session["error_info"] = "用户名或密码错误！"
    return redirect("/user/login")



@login_required
def user_logout(request):
    """ 用户退出 """
    auth.logout(request)
    return redirect("/user/login")
